<template>
  <div class="container">
    <div id="map">
    </div>
    <WinPanel v-show="panelShow" :closePanel="closePanel" :data="panelData"/>
    <div class="mask"></div>
  </div>
</template>

<script>
  import WinPanel from 'comp/common/WinPanel';

  export default {
    name: "Map",
    components: {
      WinPanel
    },
    mounted() {
      this.initMap('map');
    },
    data() {
      return {
        dict: this.$kkui.cache.get('dict'),
        ifFinished: false,
        map: null,
        markers: {},
        labels: {},

        panelShow: false,
        panelData: {},

        tempMarker: null,

        preZoom: 13,
        hiddenEvtCode:''
      }
    },
    methods: {
      initMap(id) {

        // BMapGL=>BMapGLGL
        this.map = new BMapGL.Map(id);


        this.map.setMapStyleV2({
          styleId: '93a133488d43d0f6f189a05837ea9b85'
        });
        const basePoint = new BMapGL.Point(WebCfg['mapCenter'][0], WebCfg['mapCenter'][1]);
        this.map.centerAndZoom(basePoint, WebCfg.mapZoom);
        this.map.enableScrollWheelZoom(true);
        this.panelShow = false;
        this.preZoom = 13;

        // this.map.addEventListener("click", function (e) {
        //   alert(e.point.lng + "," + e.point.lat);
        // });

        // this.map.addEventListener("zoomend", (e) => {
        //   this.renewIcon();
        // });

        var opts = {
          offset: new BMapGL.Size(10, 10)
        };
        this.map.addControl(new BMapGL.ScaleControl(opts));
        // var zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
        // this.map.addControl(zoomCtrl);


        setTimeout(() => {
          const $mask = document.querySelector('.mask');
          if ($mask) $mask.style.display = 'none';
          this.ifFinished = true
        }, 1000)

      },

      showBround() {
        //添加区划覆盖物
        const _this = this;
        var bdary = new BMapGL.Boundary();
        bdary.get("泰州市", function (rs) {
          console.log(rs);
          //获取行政区
          var count = rs.boundaries.length; //行政区域的点有多少个
          var pointArray = [];
          for (var i = 0; i < count; i++) {
            var ply = new BMapGL.Polygon(rs.boundaries[i], {
              strokeWeight: 3,
              fillOpacity: 0.1,
              fillColor: "",
              strokeColor: "#35D6EE"
            });
            _this.map.addOverlay(ply);
            pointArray = pointArray.concat(ply.getPath());
          }
          _this.map.setViewport(pointArray);
        });
      },

      addSimpleMarker(lng, lat) {
        if(this.tempMarker){
          this.map.removeOverlay(this.tempMarker);
          this.tempMarker=null;
        }
        let point = new BMapGL.Point(lng, lat);
        this.map.centerAndZoom(point,WebCfg.mapZoom);
        this.tempMarker = new BMapGL.Marker(point);
        this.map.addOverlay(this.tempMarker);
      },

      addMarker(cfg, scale2) {
        const scale = 1;

        let size = {
          'event': {
            '2': [
              new BMapGL.Size(34 * scale, 40 * scale),
              new BMapGL.Size(17 * scale, 32 * scale)
            ],
            '3': [
              new BMapGL.Size(42 * scale, 40 * scale),
              new BMapGL.Size(21 * scale, 32 * scale)
            ],
            '4': [
              new BMapGL.Size(50 * scale, 40 * scale),
              new BMapGL.Size(25 * scale, 32 * scale)
            ],
            '6': [
              new BMapGL.Size(68 * scale, 40 * scale),
              new BMapGL.Size(34 * scale, 32 * scale)
            ]
          },
          'camera': [
            new BMapGL.Size(18 * scale, 18 * scale),
            new BMapGL.Size(24 * scale, 24 * scale)
          ]
        };


        const gis = cfg.gis;


        var myIcon = null;
        if (cfg['type'] === 'camera') {
          myIcon = new BMapGL.Icon(cfg['icon'], size[cfg['type']][0], {
            anchor: size[cfg['type']][1]
          })
        } else {
          const nameLength = cfg.name.length;
          myIcon = new BMapGL.Icon(cfg['icon'], size[cfg['type']][nameLength][0], {
            anchor: size[cfg['type']][nameLength][1]
          })
        }
        const point = new BMapGL.Point(gis[0], gis[1]);
        var marker = new BMapGL.Marker(point, {icon: myIcon});
        marker.data = cfg.data || {};
        // console.log(marker);

        this.map.addOverlay(marker);
        if(this.hiddenEvtCode && this.hiddenEvtCode!==cfg.data.preData.type){
          marker.hide();
        }
        this.markers[cfg.id] = marker;

        if (0 && !cfg.labelHide) {
          let px = [8, 14, 19, 21, 32, 38];
          const offset = {
            'event': new BMapGL.Size(-px[cfg.name.length - 1] * scale || 0, -35 * scale),
            'camera': new BMapGL.Size(10, -50)
          };

          const label = new BMapGL.Label(cfg.name, {
            position: point,
            offset: offset[cfg['type']]
          });

          label.setStyle({
            color: cfg.color,
            fontSize: 10 * scale + 'px',
            border: 'none',
            background: 'none'
          });
          this.map.addOverlay(label);
          this.labels[cfg.id] = label;
        }

        marker.addEventListener("click", () => {
          this.showPanel(cfg.id)
        });
      },

      delMarker(id) {
        if (this.markers[id]) {
          this.map.removeOverlay(this.markers[id]);
          delete this.markers[id];
        }
        if (this.labels[id]) {
          this.map.removeOverlay(this.labels[id]);
          delete this.labels[id];
        }
      },

      focusGis(gis) {
        const basePoint = new BMapGL.Point(gis[0], gis[1]);
        this.map.centerAndZoom(basePoint, Math.ceil(this.map.getZoom()));
      },


      showPanel(id) {
        this.panelData = this.markers[id]['data'];
        this.panelShow = !!1;
      },

      closePanel() {
        this.panelShow = false;
      },

      renewIcon() {
        const zoom = this.map.getZoom();
        if (!this.ifFinished || !WebCfg.autoScale.enable) {
          return false;
        }
        let scale = 1;
        if (this.preZoom > zoom) { // 缩小
          if (parseInt(zoom) < 11) {
            return false;
          } else if (parseInt(zoom) === 12 || parseInt(zoom) === 11) {
            scale = 1;
          } else {
            scale = zoom / WebCfg.autoScale.zoom * WebCfg.autoScale.scale;
          }

        } else { // 放大
          scale = zoom / WebCfg.autoScale.zoom * WebCfg.autoScale.scale;
        }

        if (Object.keys(this.markers).length > 0) {
          Object.keys(this.markers).forEach(id => {
            const item = this.markers[id].data.preData;
            const _type = this.markers[id].data.type;
            this.delMarker(id);
            if (_type === 'camera') {
              let color = '';
              if (item.state === '0') {
                color = '#1296DB';
              } else if (item.state === '-1') {
                color = '#C90AF2';
              } else {
                color = WebCfg['eventColor'][item['state']];
              }
              const gis = [item['longitude'], item['latitude']];

              this.addMarker({
                type: 'camera',
                id,
                color,
                gis,
                icon: require(`@/assets/img/common/icon/camera_${color}.png`),
                labelHide: true,
                data: {
                  preData: item,
                  id,
                  type: 'camera',
                  imagePath: item['imgPath'],
                  livePath: 'ws:' + WebCfg.api['wsUrl'] + ':' + WebCfg.api.wsPort + '/' + item['videoAddress'],
                  // livePath:  'ws:'+WebCfg.api['wsUrl]+':'+(WebCfg.api.wsPort+parseInt(idx/4))+'/'+item['videoAddress'],
                  // livePath:  'ws://172.16.16.50:11507/'+item['videoAddress'],
                  state: item.state,
                  items: [
                    {
                      key: 'state',
                      label: '状态',
                      value: this.dict['camera'][item.state],
                      color
                    },
                    {
                      key: 'road',
                      label: '路段',
                      value: item['road'],
                      color
                    },
                    {
                      key: 'pos',
                      label: '位置',
                      value: item['name'],
                      color
                    }
                  ]
                },
              }, scale);
            } else {
              if (!WebCfg.autoScale.evtEnable) return false;

              const camera = item['bscCamera'];
              if (camera) {
                const id = item.id,
                  code = item['eventTypeTwoCode'],
                  color = WebCfg.eventColor[code],
                  gis = [camera['longitude'], camera['latitude']];
                let name = this.dict['event'][code];
                name = name.indexOf('-') > -1 ? name.split('-')[1] : name;

                this.map && this.addMarker({
                  type: 'event',
                  id,
                  name,
                  color,
                  gis,
                  icon: require(`@/assets/img/common/icon/event_${color}.png`),
                  data: {
                    preData: item,
                    id,
                    type: 'event',
                    videoPath: item.videoPath,
                    imagePath: item.imgPath,
                    event: item.code,
                    state: item.state,
                    items: [
                      {
                        key: 'type',
                        label: '类型',
                        value: name,
                        color
                      },
                      {
                        key: 'state',
                        label: '状态',
                        value: this.dict['status'][item.state],
                        color
                      },
                      {
                        key: 'road',
                        label: '路段',
                        value: camera['road'],
                        color
                      },
                      {
                        key: 'pos',
                        label: '位置',
                        value: camera['name'],
                        color
                      }
                    ]
                  },

                }, scale)
              }
            }

          })
        }


        this.preZoom = zoom;

      },





    },
    watch:{
      hiddenEvtCode:function f(n,o) {
        const markers=Object.values(this.markers);
        markers.forEach(marker=>{
          if(n){
            if(marker.data.preData.type===n){
              marker.show();
            }else{
              marker.hide();
            }
          }else{
            marker.show();
          }
        });
      }
    },
    beforeDestroy() {
      if (this.map && typeof this.map.destroy === 'function') {
        this.map.destroy();
      }
      this.map = null;
      this.markers = {};
      this.labels = {};

      this.panelShow = false;
      this.hiddenEvtCode='';
    },
  }
</script>

<style scoped lang="scss">
  .container {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: rgba(17, 22, 41, .8);

    #map {
      width: 100%;
      height: 100%;
      /*background-color: #000;*/

      /deep/ .anchorBL {
        img {
          display: none !important;
        }

      }

      /deep/ .BMap_scaleTxt {
        text-shadow: none !important;
        color: #999;
      }

      /deep/ .BMap_scaleBarBG {
        background-color: transparent !important;
      }

      /deep/ .BMap_scaleBar {
        background-color: #999;
      }
    }

    .mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: url("~@/assets/img/common/map_bg.png") top left repeat #000;
    }
  }


</style>
